<template>
    <div class="main">
        <div class="menu">
            <div class="active" v-if="currentNavIdx === -1">搜索结果</div>
            <div
                :class="{ active: currentNavIdx === idx }"
                v-for="(item, idx) in categories"
                @click="changeNavIdx(idx, item.id)"
            >
                {{ item.name }}
            </div>
            <div @click="toggleTheme" :class="{ red: hasToken }">切换主题</div>
            <div @click="getData(true)">强制刷新</div>
        </div>
        <div class="content">
            <search :searchEngines="searchEngines" @filter="filter"></search>
            <div>
                <template v-if="filterResults"> 搜索结果 </template>
                <template v-else>
                    <div class="search-item">
                        <div
                            :class="{
                                'search-active': currentSubCategoriesIdx == idx,
                            }"
                            v-for="(item, idx) in currentSubCategories"
                            :key="item.id"
                            @click="changeSubCategoriesIdx(idx, item.id)"
                        >
                            {{ item.name }}
                        </div>
                    </div>
                </template>
                <div class="web-container">
                    <template
                        v-for="(item, idx) in currentWebItems"
                        :key="item.id"
                    >
                        <web :item="item"></web>
                    </template>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import search from "@/components/search.vue";
import web from "@/components/web.vue";
import { get } from "@/utils/http";
import { onMounted, ref } from "vue";

const theme = ref("dark");
const themeKey = "theme";
// 收藏分类，不带关联webs和sub_web_category
const categories = ref([]);
// 左侧菜单索引
const currentNavIdx = ref(null);
// 当前收藏
const currentSubCategories = ref(null);
// 当前收藏显示的网站索引
const currentSubCategoriesIdx = ref(null);
const currentWebItems = ref(null);
// 搜索引擎
const searchEngines = ref([]);
// 收藏夹过滤
const filterResults = ref(null);
const hasToken = ref(false);
// 带关联的所有收藏夹栏目
let allCategoriesWithSub = [];

onMounted(async () => {
    document.title = "导航";
    theme.value = localStorage.getItem(themeKey) || "light";
    document.documentElement.dataset.theme = theme.value;

    await getData();

    hasToken.value =
        localStorage.getItem("local:_token") &&
        localStorage.getItem("local:_token").length > 0;
});

const getData = async (fresh = false) => {
    if (fresh) {
        const token = localStorage.getItem("local:_token");
        const tokenExpired = localStorage.getItem("local:_token_expired");
        localStorage.clear();
        localStorage.setItem("local:_token_expired", tokenExpired);
        localStorage.setItem("local:_token", token);
    }
    let localWebCache = localStorage.getItem("local:root_categories");
    let localSearchCache = localStorage.getItem("local:search_cache");
    let localAllCategoriesWithSub = localStorage.getItem(
        "local:allCategoriesWithSub",
    );
    categories.value = JSON.parse(localWebCache);
    searchEngines.value = JSON.parse(localSearchCache);
    allCategoriesWithSub = JSON.parse(localAllCategoriesWithSub);

    if (!searchEngines.value || searchEngines.value.length == 0) {
        get("/search-engines").then((resp) => {
            searchEngines.value = resp.data.items;
            localStorage.setItem(
                "local:search_cache",
                JSON.stringify(resp.data.items),
            );
        });
    }

    if (!categories.value || categories.value.length == 0) {
        let resp = await get("/web");
        if (resp.data.errCode == 0) {
            categories.value = resp.data.items;
            localStorage.setItem(
                "local:root_categories",
                JSON.stringify(resp.data.items),
            );
        }
    }
    changeNavIdx(0, categories.value[0].id);

    if (!allCategoriesWithSub || allCategoriesWithSub.length == 0) {
        get("/web/all").then((resp) => {
            allCategoriesWithSub = resp.data.items;
            localStorage.setItem(
                "local:allCategoriesWithSub",
                JSON.stringify(resp.data.items),
            );
        });
    }
};

// 左侧菜单切换
const changeNavIdx = async (idx, id) => {
    currentNavIdx.value = idx;
    const key = "local:subCategories_" + id;
    const navSub = localStorage.getItem(key);

    if (navSub && navSub.length > 5) {
        currentSubCategories.value = JSON.parse(navSub);
    } else {
        let resp = await get("/web/sub?id=" + categories.value[idx].id);
        if (resp.data.errCode == 0) {
            let subCategories = resp.data.item.sub_web_category;
            if (resp.data.item.webs.length > 0) {
                subCategories.unshift({
                    name: " ⌂ ",
                    id: 0,
                    webs: resp.data.item.webs,
                });
            }

            currentSubCategories.value = subCategories;
            localStorage.setItem(key, JSON.stringify(subCategories));
        }
    }

    changeSubCategoriesIdx(0, categories.value[idx].id);
};

const changeSubCategoriesIdx = (idx, id) => {
    currentSubCategoriesIdx.value = idx;
    if (currentSubCategories.value[idx].name.indexOf("⌂") > -1) {
        currentWebItems.value = currentSubCategories.value[idx].webs;
    } else {
        const key = "local:webItems_" + id;
        const webItems = localStorage.getItem(key);
        if (webItems && webItems.length > 0) {
            currentWebItems.value = JSON.parse(webItems);
        } else {
            get("/web/sub?id=" + id).then((resp) => {
                if (resp.data.errCode == 0) {
                    currentWebItems.value = resp.data.item.webs;
                    localStorage.setItem(
                        key,
                        JSON.stringify(resp.data.item.webs),
                    );
                }
            });
        }
    }
};

const toggleTheme = () => {
    theme.value = theme.value === "light" ? "dark" : "light";
    document.documentElement.dataset.theme = theme.value;
    localStorage.setItem(themeKey, theme.value);
};

// 收藏夹过滤
const filter = (words) => {
    let result = [];
    for (let item of allCategoriesWithSub) {
        for (let sub of item.sub_web_category) {
            for (let web of sub.webs) {
                if (
                    web.title.toLowerCase().indexOf(words) > -1 ||
                    web.description.toLowerCase().indexOf(words) > -1
                ) {
                    result.push(web);
                }
            }
        }
    }
    currentSubCategories.value = [];
    currentWebItems.value = result;
    currentNavIdx.value = -1;
};
</script>

<style>
.main {
    display: flex;
    flex-direction: row;
    color: var(--txt);
    height: 100vh;
}

.menu {
    min-width: 200px;
    background-color: var(--bg1);
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.active {
    background-color: var(--bg2);
}

.menu > div {
    padding: 10px;
    cursor: pointer;
}

.content {
    padding: 10px 20px;
    flex: 1;
    overflow-y: scroll;
    scrollbar-width: none;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.content::-webkit-scrollbar {
    display: none;
}

.search-item {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.search-item > div {
    padding: 10px;
    cursor: pointer;
}

.search-active {
    background-color: var(--bg1);
    border-radius: 5px;
}

.web-container {
    margin: 20px auto;
    width: 96%;
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 20px;
    break-inside: avoid;
    box-sizing: border-box;
    justify-items: stretch;
    align-items: stretch;
    justify-content: stretch;
    align-content: stretch;
}
@media screen and (max-width: 1900px) {
    .web-container {
        grid-template-columns: repeat(4, 1fr);
    }
}

@media screen and (max-width: 1600px) {
    .web-container {
        grid-template-columns: repeat(3, 1fr);
    }
}

@media screen and (max-width: 1300px) {
    .web-container {
        grid-template-columns: repeat(2, 1fr);
    }
}
@media screen and (max-width: 1000px) {
    .web-container {
        grid-template-columns: repeat(1, 1fr);
    }
}

.red {
    color: red;
}
</style>
